package integraltesk

import (
	"context"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/setting/rpc/settingclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateIntegralTaskLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateIntegralTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateIntegralTaskLogic {
	return &UpdateIntegralTaskLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateIntegralTaskLogic) UpdateIntegralTask(req *types.UpdateIntegralTaskReq) (*types.BaseMsgResp, error) {
	logx.Infof("UpdateIntegralTask : %+v ", req)
	if len(req.Ids) > 0 {
		res, err := l.svcCtx.SettingRpc.BackendUpdateIntegralTask(l.ctx, &settingclient.IntegralTaskInfo{
			Status: req.Status,
			Ids:    req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}
	var integralTaskInfo = &settingclient.IntegralTaskInfo{}
	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}
	integralTaskInfo.Id = req.Id

	if req.RuleName != nil && len(strings.TrimSpace(*req.RuleName)) > 0 {
		integralTaskInfo.RuleName = req.RuleName
	}

	if req.RuleSlug != nil && len(strings.TrimSpace(*req.RuleSlug)) > 0 {
		integralTaskInfo.RuleSlug = req.RuleSlug
	}

	if req.RuleType != nil && *req.RuleType > 0 {
		integralTaskInfo.RuleType = req.RuleType
	}

	if req.PicId != nil && *req.PicId > 0 && req.PicUrl != nil && len(strings.TrimSpace(*req.PicUrl)) > 0 {
		integralTaskInfo.PicId = req.PicId
		integralTaskInfo.PicUrl = req.PicUrl
	}

	//if req.Frequency != nil && *req.Frequency > 0 {
	//	integralTaskInfo.Frequency = req.Frequency
	//}

	if req.Points != nil && *req.Points > 0 {
		integralTaskInfo.Points = req.Points
	}

	if req.EffectiveTime != nil && len(strings.TrimSpace(*req.EffectiveTime)) > 0 {
		integralTaskInfo.EffectiveTime = req.EffectiveTime
	}

	if req.Sort != nil && *req.Sort > 0 {
		integralTaskInfo.Sort = req.Sort
	}

	if req.Ip != nil && len(strings.TrimSpace(*req.Ip)) > 0 {
		integralTaskInfo.Ip = req.Ip
	}

	if req.Description != nil && len(strings.TrimSpace(*req.Description)) > 0 {
		integralTaskInfo.Description = req.Description
	}

	if req.Status != nil && *req.Status > 0 {
		integralTaskInfo.Status = req.Status
	}

	//createdBy := pointy.GetPointer(jwt.GetBackendUserId(l.ctx))
	res, err := l.svcCtx.SettingRpc.BackendUpdateIntegralTask(l.ctx, integralTaskInfo)
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
